package com.atguigu.gulimall.auth.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.atguigu.common.constant.AuthServerConstant;
import com.atguigu.common.to.SocialUser;
import com.atguigu.common.utils.HttpUtils;
import com.atguigu.common.utils.R;
import com.atguigu.common.vo.MemberRespVO;
import com.atguigu.gulimall.auth.feign.MemberFeignService;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;

/**
 * @author wzb
 * @version V1.0
 * @Package com.atguigu.gulimall.auth.controller
 * @date 2022-08-17 10:09
 * @Copyright ©
 */
@Controller
@SuppressWarnings({"all"})
@Slf4j
public class OAuth2Controller {


    @Autowired
    MemberFeignService memberFeignService;


    //用户同意授权 使用 code 获取 token，使用 token 获取 用户数据
    //http://auth.gulimall.com/oauth2/gitee/success

    @RequestMapping("/oauth2.0/gitee/success")
    public String authorize(@RequestParam("code") String code, HttpSession session) throws Exception {
        //1.使用code换取token，换取成功继续2，否则重定向至登录页
        Map<String, String> query = new HashMap<>();
        query.put("client_id", "0b063a05ca4ef7a2e87e98f216b638196116bccdf4b1a09f4ac50031ac110dae");
        query.put("client_secret", "98580ca60242d28682ee735c14c3830b7b289b03cf3db224ccc0f684a2ebf76a");
        query.put("grant_type", "authorization_code");
        query.put("redirect_uri", "http://auth.gulimall.com/oauth2.0/gitee/success");
        query.put("code", code);

        // 发送 post 请求获取 token
        //https://gitee.com/oauth/token?grant_type=authorization_code&code={code}&client_id={client_id}&redirect_uri={redirect_uri}&client_secret={client_secret}
        HttpResponse response = HttpUtils.doPost("https://gitee.com", "/oauth/token", "post", new HashMap<String, String>(), query, new HashMap<String, String>());
        Map<String, String> errors = new HashMap<>();
        if (response.getStatusLine().getStatusCode() == 200) {
            //3.调用 member 远程接口进行 oauth 登录，登录成功则转发至首页并携带返回用户信息，否则转发至登录页
            String json = EntityUtils.toString(response.getEntity());
            SocialUser socialUserTo = JSON.parseObject(json, new TypeReference<SocialUser>() {
            });
            //拿着 accessToken 查询用户信息
            if (socialUserTo != null && (!StringUtils.isEmpty(socialUserTo.getAccess_token()))) {

                Map<String, String> queryAccessToken = new HashMap<>();
                queryAccessToken.put("access_token", socialUserTo.getAccess_token());

                Map<String, String> queryHeader = new HashMap<>();
                queryHeader.put("Content-Type", "application/json;charset=UTF-8");

                //发送请求
                //https://gitee.com/api/v5/user?access_token={access_token}
                HttpResponse response1 = HttpUtils.doGet("https://gitee.com", "/api/v5/user", "get", queryHeader, queryAccessToken);

                if (response1.getStatusLine().getStatusCode() == 200) {
                    //请求成功
                    String json1 = EntityUtils.toString(response1.getEntity());

                    //获取 user_info 的 id
                    //转成 SocialUserTo 方便调用服务
                    SocialUser socialUserTo1 = JSON.parseObject(json1, new TypeReference<SocialUser>() {
                    });
                    socialUserTo1.setAccess_token(socialUserTo.getAccess_token());
                    socialUserTo1.setExpires_in(socialUserTo.getExpires_in());

                    //TODO 社交帐号登录与注册为一体
                    //================远程调用登录==================
                    R oauthLogin = memberFeignService.oauthLogin(socialUserTo1);
                    //2.1 远程调用成功，返回首页并携带用户信息
                    if (oauthLogin.getCode() == 0) {
                        MemberRespVO memberRespVO = oauthLogin.getData(new TypeReference<MemberRespVO>() {
                        });
                        log.info("登录成功，用户信息" + memberRespVO.toString());
                        session.setAttribute(AuthServerConstant.LOGIN_USER, memberRespVO);
                        return "redirect:http://gulimall.com";
                    } else {
                        //2.2 否则返回登录页
                        errors.put("msg", "登录失败，请重试");
                        session.setAttribute("errors", errors);
                        return "redirect:http://auth.gulimall.com/login.html";
                    }
                } else {
                    errors.put("msg", "获取第三方授权失败，请重试(获取用户信息失败)");
                    session.setAttribute("errors", errors);
                    return "redirect:http://auth.gulimall.com/login.html";
                }
            }
        }
        errors.put("msg", "获取第三方授权失败，请重试(获取token失败)");
        session.setAttribute("errors", errors);
        return "redirect:http://auth.gulimall.com/login.html";
    }

}


